package com.king.hessian;

import java.util.concurrent.atomic.AtomicInteger;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ProxyWrapper {

    /**
     * 统计失败次数的时间区间
     */
    private int INTERVAL;

    /**
     * 被代理对象
     */
    private final Object proxy;

    /**
     * 调用服务失败的计数器
     */
    private final AtomicInteger failTimeCounter = new AtomicInteger();

    /**
     * 允许失败的最多次数
     */
    private final int maxFail;

    /**
     * 最后一次失败的时间(seconds)
     */
    private volatile int failTime = -1;


    /**
     * 是否做热切开关
     */
    private final boolean downDetectAble;


    ProxyWrapper(Object proxy, int failTimeout, int maxFail) {
        this.proxy = proxy;
        this.maxFail = maxFail;
        this.downDetectAble = (failTimeout > 0 && maxFail > 0);
        INTERVAL = failTimeout;
    }

    public Object getProxy() {
        return proxy;
    }

    public void fail() {
        if (!downDetectAble) {
            return;
        }

        this.failTimeCounter.incrementAndGet();
        if (failTime <= 0) {
            failTime = (int) (System.currentTimeMillis() / 1000);
        }

    }

    public boolean isDown() {
        if (!downDetectAble) {
            return false;
        }

        int failTimeLocal = failTime;
        if (failTimeLocal > 0) {
            int currentTimeSeconds = (int)(System.currentTimeMillis() / 1000);
            if (currentTimeSeconds - failTimeLocal < INTERVAL) {
                return failTimeCounter.get() > maxFail;
            } else {
                reset();
                return false;
            }
        } else {
            return false;
        }
    }


    public void reset() {
        this.failTimeCounter.set(0);
        this.failTime = -1;
    }

    public int getFailCount() {
        return this.failTimeCounter.get();
    }
}
